class Chatroom < ActiveRecord::Base
  
  # Declarations
  has_many :users
  has_many :messages
  
  # Validations
  validates_presence_of :name, :scope
  validates_uniqueness_of :name
  
  attr_accessor :password_confirmation
  validates_confirmation_of :password
  
  # Checks for password if scope == private(0)
  def validate
    if scope == 0
      errors.add_to_base("No password entered!") if password.blank?
    end
  end
  
  # Virtual attribute password
  def password
    @password
  end
  
  def password=(password)
    @password = password
    return if password.blank?
    create_salt
    self.password_hashed = Chatroom.encrypted_password(password, self.password_salt)
  end
  
  private  
  
  def self.authenticate(chatroom_id, password)
    chatroom = Chatroom.find(chatroom_id)
    if chatroom
      if chatroom.password_hashed == Chatroom.encrypted_password(password, chatroom.password_salt)
        return chatroom
      else
        chatroom = nil
        return chatroom
      end
    end
  end
  
  def self.encrypted_password(password, salt)
    word = "chat"
    string_to_hash = password + salt + word
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_salt
    self.password_salt = self.object_id.to_s + rand.to_s
  end
  
  
end
